package com.yanqu.road.server.cmd.patrons;

import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.PatronsPb;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.pb.patrons.PatronsProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.server.command.Cmd;

import java.util.Map;

@Cmd(code = Protocol.S_PATRONS_UPGRADE, desc = "门客升级")
public class PatronsUpgradeCmd extends AbstractCommand {

	int patronsId;

	int times;

	private int goodsIndex;

	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		PatronsProto.PatronsUpgradeReqMsg reqMsg = PatronsProto.PatronsUpgradeReqMsg.parseFrom(packet.getBytes());
		patronsId = reqMsg.getPatronsId();
		times = reqMsg.getTimes();
		if(reqMsg.hasIndex()){
			goodsIndex = reqMsg.getIndex();
		}
		return true;
	}

	@Override
	public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
		if (times > 1) {
			String[] split = GameConfig.PATRONS_TEN_UPGRADE_LIMIT_PARAM.split(";");
			int patronsNum = Integer.parseInt(split[0]);
			int patronsLv = Integer.parseInt(split[1]);
			Map<Integer, UserPatrons> userPatronsMap = player.getModule(PatronsModule.class).getUserPatronsMap();
			int num = 0;
			for (UserPatrons patrons : userPatronsMap.values()) {
				if (patrons.getLevel() >= patronsLv) {
					num++;
				}
			}
			if (num < patronsNum) {
				ret = GameErrorCode.E_PATRONS_LEVEL_NO_ENOUGH;
				return;
			}
		}
		ret = player.getModule(PatronsModule.class).patronsUpgrade(patronsId, times, goodsIndex);
	}

	@Override
	public void sendData(GamePlayer player) {
		PatronsProto.PatronsUpgradeRespMsg.Builder respMsg = PatronsProto.PatronsUpgradeRespMsg.newBuilder();
		respMsg.setRet(ret);
		UserPatrons userPatrons = player.getModule(PatronsModule.class).getUserPatrons(patronsId);
		PatronsProto.PatronsTempMsg.Builder patronsMsg = PatronsPb.parsePatronsTempMsg(userPatrons);
		if(null != patronsMsg) {
			respMsg.setPatrons(patronsMsg);
		}
		player.sendPacket(Protocol.U_PATRONS_UPGRADE, respMsg);
	}

}
